<template>
  <div class="login-panel">
    <!-- 登录面板标题，包含关闭按钮 -->
    <div class="title drag">
      <span>SweetCircle</span>
    </div>
    <!-- 登录表单容器 -->
    <div class="login-form">
      <!-- 使用Element UI的表单组件进行登录注册信息输入 -->
      <el-form :model="fromData" label-width="0px" @submit.prevent>
        <!-- 邮箱输入项 -->
        <!--      输入-->
        <el-form-item>
          <el-input v-model.trim="fromData.email" clearable placeholder="请输入邮箱" size="large">
            <template #prefix>
              <span class="iconfont icon-email"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 昵称输入项，仅在注册时显示 -->
        <el-form-item v-if="isLogin === 1">
          <el-input
            v-model.trim="fromData.nickName"
            clearable
            placeholder="请输入昵称"
            size="large"
          >
            <template #prefix>
              <span class="iconfont icon-user-nick"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 密码输入项 -->
        <el-form-item>
          <el-input
            v-model.trim="fromData.password"
            clearable
            placeholder="请输入密码"
            show-password
            size="large"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 确认密码输入项，仅在注册时显示 -->
        <el-form-item v-if="isLogin !== 0">
          <el-input
            v-model.trim="fromData.confirmPassword"
            clearable
            placeholder="请输入确认密码"
            show-password
            size="large"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 验证码输入项 -->
        <el-form-item>
          <div class="captcha-container">
            <el-input
              v-model.trim="fromData.captcha"
              clearable
              placeholder="请输入验证码"
              size="large"
              @keyup.enter="submit"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
            <img :src="captchaPath" class="captcha-img" @click="getCaptcha"/>
          </div>
        </el-form-item>
        <!-- 登录、注册、重置密码按钮 -->
        <el-form-item>
          <el-button v-if="isLogin === 0" class="login-btn" type="primary" @click="submit"
          >登 录
          </el-button>
          <el-button v-if="isLogin === 1" class="login-btn" type="primary" @click="submit"
          >注 册
          </el-button>
          <el-button v-if="isLogin === 2" class="login-btn" type="primary" @click="submit"
          >重 置 密 码
          </el-button>
        </el-form-item>
      </el-form>
      <!-- QQ登录按钮 -->
      <!--qq登录-->
      <img alt="" class="qq-login" src="../assets/img/qq.png" />
      <!-- 登录/注册/重置密码切换面板 -->
      <div v-if="isLogin === 0" class="row-op-panel">
        <span class="a-link" @click="changeIsLogin(2)">忘记密码</span>&nbsp;|&nbsp;
        <span class="a-link" @click="changeIsLogin(1)">注册账号</span>
      </div>
      <div v-if="isLogin !== 0" class="row-op-panel">
        <span class="a-link" @click="changeIsLogin(0)">已有账号,登录</span>
      </div>
    </div>
  </div>
  <WindowOperation :closeType="0" :showMax="false" :showMin="false" :showSetTop="false"></WindowOperation>
  <div class="card2 no-drag" v-if="dialogTableVisible">
    <el-card class="info">
      <div>账号在别处登录，是否继续登录</div>
      <div class="button">
        <el-button @click="loginSuccess" type="primary">继续</el-button>
        <el-button @click="dialogTableVisible=false" type="primary">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import Api from '#/utils/Api'
import WindowOperation from '#/components/WindowOperation.vue'
import { ElLoading, ElMessage } from 'element-plus'
import Tool from '#/utils/Tool'
import { useContactPersonInfoStore } from '#/stores/ContactPersonInfoStore'
import { useUserInfoStore } from '#/stores/UserInfoStore'
import Re from '@imengyu/vue3-context-menu/lib/vue3-context-menu.es'

const userInfoStore = useUserInfoStore()
const contactPersonInfoStore = useContactPersonInfoStore() // 存储联系人信息  用户的所有联系人
const router = useRouter()
let captchaPath = ref('')  // 验证码路径
const dialogTableVisible = ref(false)  // 显示卡片账号异地登录 是否强制下线重新登录
const loginResponse ={}  // 登录响应



// 加载前先获取验证码
onMounted(() => {
  getCaptcha()
})

const fromData = ref({
  email: 'admin@admin.com',
  password: 'zxc123456',
  nickName: '',
  confirmPassword: '',
  captcha: '',
  captchaKey: ''
})

// 控制登录、注册、重置密码状态的引用
const isLogin = ref(0)

const resetFromData = () => {
  fromData.value = {
    email: '',
    password: '',
    nickName: '',
    confirmPassword: '',
    captcha: '',
    captchaKey: ''
  }
}

const changeIsLogin = (val) => {
  window.ipcRenderer.send('switchWindow', val)
  resetFromData()
  isLogin.value = val
  getCaptcha()
}

const getCaptcha = async () => {

    let res = await Api.captcha()
    captchaPath.value = res.data.captchaBase64
    fromData.value.captchaKey = res.data.captchaKey
}

const submit = () => {
  const { res, msg } = Tool.parameterValidation(fromData, 0)
  if (!res) {
    ElMessage.error(msg)
    return
  }


  if (isLogin.value === 0) {
    _login()
  } else if (isLogin.value === 1) {
    _register()
  } else {
    _resetPassword()
  }
}


const _login = async () => {
  const response = await Api.login(fromData.value)
  if (response.code === 200) {
    Object.assign(loginResponse,response)
    if(response.data.alreadyLogin){
      dialogTableVisible.value = true
    }else{
      loginSuccess()
    }
  }else {
    getCaptcha().then()
    ElMessage.error(response.msg)
  }
}

const _register = async () => {
  const response = await Api.register(fromData.value)
  if (response.code === 200) {
    ElMessage.success(response.msg)
    changeIsLogin(0)
  } else {

    getCaptcha().then()
    ElMessage.error(response.msg)
  }
}

// 重置密码逻辑
const _resetPassword = async () => {
  const response = await Api.resetPassword(fromData.value)
  if (response.code === 200) {
    ElMessage.success(response.msg)
    changeIsLogin(0)
  } else {

    getCaptcha().then()
    ElMessage.error(response.msg)
  }
}
const loginSuccess = async ()=>{
  if(dialogTableVisible.value){
    const arg = {
      messageContent:"账号在别处登录",
      messageType:7,  // 账号在别处登录 强制下线
      messageCode:1,  // 1发送给用户 2发送给群聊
      contactId:loginResponse.data.userInfo.userId,
    }
   const res = await Api.sendMessage(arg)
    if(res.code === 200) {
      openMainWindows()
    }
  }else{
    openMainWindows()
  }
}
const openMainWindows = ()=>{
  dialogTableVisible.value = false
  ElMessage.success(loginResponse.msg)
  window.ipcRenderer.send('loginSuccess',loginResponse.data.userInfo)
  userInfoStore.setUserInfo(loginResponse.data.userInfo, true)
  contactPersonInfoStore.setContactPersonInfoList(loginResponse.data.contactList)
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: '#ffffff'
  })
  setTimeout(() => {
    router.push('/main').then()
    setTimeout(() => {
      loading.close()
    }, 500)
  }, 500)
}




</script>
<style lang="scss" scoped>

.loading-panel {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 2;

}

.login-panel {
  display: flex;
  flex-direction: column;
  align-items: center;

  .title {
    display: flex;
    width: 100%;
    font-size: 15px;
    height: 25px;
    align-items: center;
    justify-content: center;
  }

  .login-form {
    //margin: 0 auto;
    text-align: center;
    padding: 25px;
    width: 300px;
    background: white;
    border-radius: 10px;

    :deep(.el-input__wrapper) {
      padding-left: 5px;
      box-shadow: none;
      border-bottom: 1px solid #ddd;
    }
  }

  .captcha-container {
    display: flex;

    .captcha-img {
      cursor: pointer;
      flex: 1;
      width: 120px;
      height: 40px;
      margin-left: 2px;
    }
  }

  .login-btn {
    width: 100%;
  }

  .qq-login {
    width: 30px;
    height: 30px;
  }

}


.card2 {
  width: 100%;
  height: 100%;
  float: left;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.8);

  .button {
    margin-top: 15px;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-button {
      width: 100px;
    }
  }
}
</style>
